from sqlalchemy import Column, Integer, String, DateTime, Date
from database import Base
from sqlalchemy.orm import relationship
from sqlalchemy import ForeignKey
from datetime import datetime

class RecordOfMedicine(Base):
    __tablename__ = "records_of_medicine"

    ID = Column(Integer, primary_key=True, index=True, autoincrement=True)
    phar_ID = Column(Integer, ForeignKey("pharmacist.ID"))
    con_date = Column(Date)
    dispensed_at = Column(DateTime, default=datetime.utcnow)
    medicine_ID = Column(Integer)
    medicine_name = Column(String(100))
    number = Column(Integer)
    patient_ID = Column(Integer, ForeignKey("patient.ID"))
    total_price = Column(Integer)

    # 定义关系
    pharmacist = relationship("Pharmacist", back_populates="dispensing_records")
    patient = relationship("Patient", back_populates="medicine_records")

    def to_dict(self):
        return {
            "ID": self.ID,
            "phar_ID": self.phar_ID,
            "con_date": self.con_date.isoformat() if self.con_date else None,
            "dispensed_at": self.dispensed_at.isoformat() if self.dispensed_at else None,
            "medicine_ID": self.medicine_ID,
            "medicine_name": self.medicine_name,
            "number": self.number,
            "patient_ID": self.patient_ID,
            "total_price": self.total_price
        }

    @classmethod
    def from_dict(cls, data: dict) -> "RecordOfMedicine":
        valid_keys = set(cls.__table__.columns.keys())
        return cls(**{k: v for k, v in data.items() if k in valid_keys})